package com.awakensoftware.hunterserver.web.rest;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;

import com.awakensoftware.communicationprotocol.contractobjects.ContractObjectBase;
import com.awakensoftware.communicationprotocol.contractobjects.errors.ErrorContractObject;
import com.awakensoftware.hunterserver.serverentities.ServerEntityBase;
import com.awakensoftware.hunterserver.transformers.TransformerBase;
import com.awakensoftware.hunterserver.web.ControllerBase;

public abstract class RestEntityControllerBase<TServerEntityType extends ServerEntityBase, TContractObjectType extends ContractObjectBase>
		extends ControllerBase<ErrorContractObject> {

	@Autowired
	protected TransformerBase<TServerEntityType, TContractObjectType> transformer;

	protected TContractObjectType getRestResponseFromServerEntity(TServerEntityType serverEntity) {
		return transformer.transformFromServerEntityToContractObject(serverEntity);
	}
	
	protected List<TContractObjectType> getRestResponseFromServerEntities(List<TServerEntityType> serverEntities) {		
		List<TContractObjectType> contractObjectsList = new ArrayList<TContractObjectType>(serverEntities.size());
		for (TServerEntityType serverEntity : serverEntities) {
			contractObjectsList.add(transformer.transformFromServerEntityToContractObject(serverEntity));
		}
		return contractObjectsList;		
	}

	protected TServerEntityType getServerEntityfromRestRequest(TContractObjectType contractObject) {
		return transformer.transformFromContractToServerEntity(contractObject);
	}

	@Override
	protected HttpHeaders getResponseHeaders() {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "application/json; charset=utf-8");
		return responseHeaders;
	}

	@Override
	protected abstract ErrorContractObject handleException(Exception ex, HttpServletRequest request);

	protected ErrorContractObject getErrorContractObject(Exception ex) {
		ErrorContractObject error = new ErrorContractObject();
		error.setMessage(ex.getMessage());
		return error;
	}

}
